package com.hmyd.hmyd_android.ui;

import java.net.SocketTimeoutException;

import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dialog.NormalDialog;
import com.hmyd.hmyd_android.dialog.NormalDialogListener;
import com.hmyd.hmyd_android.dto.Base;
import com.hmyd.hmyd_android.utils.HttpExceptionHandler;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.PreferencesUtils;
import com.hmyd.hmyd_android.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.shangzhu.apptrack.AppTrack_2423;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import android.app.Dialog;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.TextView;

/**
 * 所有Activity的基类
 * 
 * @author sun_t
 * 
 */
public abstract class BasicActivity extends FragmentActivity {
	// 是否允许全屏
	private boolean mAllowFullScreen = false;
	private Dialog progressDialog = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 启动xUtils视图注入
		ViewUtils.inject(this);

		Utils.windowScreenSize(this);

		// 竖屏设置
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		if (mAllowFullScreen) {
			// 取消标题
			requestWindowFeature(Window.FEATURE_NO_TITLE);
		}

		// 添加到Activity堆栈中统一管理
		AppBasic.getInstance().init();
		AppBasic.getInstance().addActivity(this);
		PushAgent.getInstance(this).onAppStart();
		
		// 3、设置参数
		setParams();
		
		/* 99检测工具 */
		AppTrack_2423.setShowLog(false);
		AppTrack_2423.setOzAppVer("惠民益贷" + Utils.getVersionName(this) + "&version");
		AppTrack_2423.setOzChannel(Utils.getUmengChannel(this) + "&channel");
		AppTrack_2423.setOzSysPara("name=惠民益贷&author=hmyd");
		AppTrack_2423.setOzSource("Android");

		AppTrack_2423.countAppOpen(this);
		
	}
	
	RequestParams pm;
	
	/**
	 * 发送请求
	 * @param postId      // 唯一标识
	 * @param url		  // 请求地址
	 * @param methodType  // 请求方法类型
	 * @param params	  // 请求参数
	 */
	public void onRequest(final int postId,final String url,final HttpMethod methodType,RequestParams params){
		if (!Utils.isConnectByNet(this) && !Utils.isConnectByMobile(this) && !Utils.isConnectByWifi(this)) {
			MyToast.showHMToast(this, false, getString(R.string.network));
			return;
		}
		if(methodType==null){
			return;
		}

		final HttpUtils http = AppBasic.getHttpUtils();
		if(params==null){
			params = new RequestParams();
		}
		
		pm = params;
		
		// 如果cookieStore存在   http自动管理cookieStore
		if (AppBasic.cookieStore != null && AppBasic.cookieStore.getCookies().size() > 0) {
			http.configCookieStore(AppBasic.cookieStore);
		}
		
		// 获取时间戳
		String timestamp = String.valueOf(System.currentTimeMillis() + 
						PreferencesUtils.getLong(this, PreferencesUtils.TIMEDIFFERENCE));
		
		params.addHeader("hm-app", "HMA");
		params.addHeader("hm-app-v", Utils.getVersionName(this));
		params.addHeader("hm-app-m", "Prod");
		params.addHeader("hm-app-c", Utils.getUmengChannel(this));
		params.addHeader("hm-app-id",AppBasic.mDeviceId);
		params.setHeader("hmyd-app-timestamp", timestamp);
		
		// 签名信息放入头文件
		final String subString = url.substring(UrlConstant.BASEURL.length());
		if(TextUtils.isEmpty(AppBasic.key) && subString.equals("/app/nommal/v1/str")){
			params.setHeader("hmyd-app-sign", Utils.getSign(this,subString+timestamp));
		}else if(!TextUtils.isEmpty(AppBasic.key) && !subString.equals("/app/nommal/v1/currentTimeMillis")){
			params.setHeader("hmyd-app-sign", Utils.getSign(this,subString+timestamp+AppBasic.key));
		}else if(TextUtils.isEmpty(AppBasic.key) && !subString.equals("/app/nommal/v1/currentTimeMillis")){
			return;
		}
		
		progressDialog = new Dialog(BasicActivity.this,R.style.progress_dialog);
		progressDialog.setContentView(R.layout.dialog_waiting);
		progressDialog.setCancelable(false);
		progressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
		TextView msg = (TextView) progressDialog.findViewById(R.id.id_tv_loadingmsg);
		msg.setTextSize(12);
		msg.setText("卖力加载中...");
		
		HttpHandler<String> handler = http.send(methodType, url, params, new RequestCallBack<String>() {
			
			/**
			 * 开始请求
			 */
			@Override
			public void onStart() {
				if (!isFinishing()) {
					progressDialog.show();
				}
			}
			
			/**
			 * 取消请求
			 */
			@Override
			public void onCancelled() {
				if (progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
			}
			
			/**
			 * 设置进度条当前信息
			 */
			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				
			}

			/**
			 * 请求成功
			 */
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				if (progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
				
				DefaultHttpClient dh = (DefaultHttpClient) http.getHttpClient();
            	if((UrlConstant.LOGIN_SHORT_URL.equals(subString) ||  UrlConstant.REGISTER_SHORT_URL.equals(subString))
            			&& dh.getCookieStore()!=null 
            			&& dh.getCookieStore().getCookies().size()>0){
            		AppBasic.cookieStore = dh.getCookieStore();
            	}else{
//            		LogUtils.d(postId+"----"+url);
            		Utils.printOutToConsole(postId+"----"+url);
            	}
				
            	
            	if(responseInfo.getFirstHeader("server-time")!=null && responseInfo.getFirstHeader("server-time").getValue()!=null){
            		AppBasic.ServerTime = Long.valueOf(responseInfo.getFirstHeader("server-time").getValue());
            	}
            	
            	onPostSuccess(postId,responseInfo.result);
			}

			/**
			 * 请求失败
			 */
			@Override
			public void onFailure(HttpException error, String msg) {
				if (progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
				
				if (error.getCause() instanceof SocketTimeoutException || error.getCause() instanceof ConnectTimeoutException) {
					error.getCause().printStackTrace();
					
					showErrorDailog(postId, url, methodType, pm);
				}
				
				try {
					onPostFailure(postId, msg);

					if(!TextUtils.isEmpty(msg)){
						Gson gson = new Gson();
						java.lang.reflect.Type type = new TypeToken<Base>() {}.getType();
						Base base = gson.fromJson(msg, type);
						if(base!=null && base.error!=null){
							MyToast.showHMToast(BasicActivity.this, false, base.error.message);
							HttpExceptionHandler.exceptionHandler(BasicActivity.this, base.error.code);
						}
					}
				} catch (JsonSyntaxException e) {
					e.printStackTrace();
				}
			}
			
		});
	}
	
	/**
	 * 请求成功
	 * @param postId 请求通道ID
	 * @param msg 成功返回数据
	 */
	public abstract void onPostSuccess(int postId,String msg);
	
	/**
	 * 请求失败
	 * @param postId 请求通道ID
	 * @param msg 失败返回数据
	 */
	public abstract void onPostFailure(int postId,String msg);
	
	
	// 弹出错误提示框
	public void showErrorDailog(final int postId,final String url,final HttpMethod methodType,final RequestParams params) {
		final NormalDialog cd = new NormalDialog(this,
				R.style.calculatorDialog, new NormalDialogListener() {
			@Override
			public void ok() {
				reConnect(postId, url, methodType, params);
			}

			@Override
			public void cancle() {
				AppBasic.getInstance().exitSystem();
			}

			@Override
			public void closed() {
				AppBasic.getInstance().exitSystem();
			}

		}, getString(R.string.alert),
		getString(R.string.timeout),
		getString(R.string.rerequest),
		getString(R.string.exit));
		
		if(null != cd){
			this.runOnUiThread(new Runnable() {

				@Override
				public void run() {
					cd.show();
				}
			});
		}
	}
	
	/**
	 * 请求超时，重建加密通道
	 */
	private void reConnect(int postId,String url,HttpMethod methodType,RequestParams params){
		onRequest(postId, url, methodType, params);
	}
	
	/**
	 * 获取信息是否允许全屏
	 * @param allowFullScreen
	 */
	public void setAllowFullScreen(boolean allowFullScreen){
		this.mAllowFullScreen = allowFullScreen;
	}
	
	/**
	 * 设置控件参数
	 */
	protected abstract void setParams();
	
	
	/**
	 * 添加 Home Title 触摸监听事件（必须要添加在子类中）
	 */
	protected OnTouchListener touch = new OnTouchListener() {
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int X = (int) event.getX();
			if (X < Utils.screenWidth_ / 5) {
				leftButton();
			} else if (X > Utils.screenWidth_ * 4 / 5){
				rightButton();
			}
			return false;
		}
	};
	/*@OnTouch(R.id.home_title)
	protected void onTouch(View v, MotionEvent event) {
		int X = (int) event.getX();
		if (X < Utils.screenWidth_ / 5) {
			leftButton();
		} else if (X > Utils.screenWidth_ * 4 / 5){
			rightButton();
		}
	}*/
	
	/**
	 * Home Title 左侧触摸事件调用方法
	 */
	protected abstract void leftButton();
	
	/**
	 * Home Title 右侧触摸事件调用方法
	 */
	protected abstract void rightButton();

	@Override
	protected void onResume() {
		super.onResume();
//		MobclickAgent.onResume(this);
//		AppTrack_2423.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
//		MobclickAgent.onPause(this);
//		AppTrack_2423.onPause(this);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (progressDialog !=null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	};
}
